<?php
require_once __DIR__ . '/../functions.php';

header('Content-Type: application/json');

// 检查登录
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$settlementId = intval($_GET['id'] ?? 0);
$userId = $_SESSION['user_id'];

if ($settlementId <= 0) {
    echo json_encode(['success' => false, 'message' => '结算记录ID无效']);
    exit;
}

// 获取结算详情，确保是当前用户的
$db = getDB();
$stmt = $db->prepare("SELECT s.* FROM settlements s 
                     WHERE s.id = ? AND s.user_id = ?");
$stmt->execute([$settlementId, $userId]);
$settlement = $stmt->fetch();

if (!$settlement) {
    echo json_encode(['success' => false, 'message' => '结算记录不存在或无权限查看']);
    exit;
}
// 处理结算截图
$screenshots = json_decode($settlement['settlement_screenshots'] ?? '[]', true);
$settlement['settlement_screenshots'] = [];
if (!empty($screenshots) && is_array($screenshots)) {
    foreach ($screenshots as $screenshot) {
        if (!empty($screenshot)) {
            $settlement['settlement_screenshots'][] = UPLOAD_URL . 'settlements/' . $screenshot;
        }
    }
}
// 获取结算明细记录
$stmt = $db->prepare("SELECT sd.*, o.product_name, o.tracking_no, o.order_amount 
                     FROM settlement_details sd 
                     LEFT JOIN orders o ON sd.order_id = o.id 
                     WHERE sd.settlement_id = ? 
                     ORDER BY sd.created_at DESC");
$stmt->execute([$settlementId]);
$settlementDetails = $stmt->fetchAll();

// 处理明细记录的截图
foreach ($settlementDetails as &$detail) {
    if (!empty($detail['screenshots'])) {
        $screenshots = json_decode($detail['screenshots'], true);
        $detail['screenshot_urls'] = [];
        if (!empty($screenshots) && is_array($screenshots)) {
            foreach ($screenshots as $screenshot) {
                if (!empty($screenshot)) {
                    $detail['screenshot_urls'][] = UPLOAD_URL . 'settlements/' . $screenshot;
                }
            }
        }
    }
}

$settlement['details'] = $settlementDetails;
// 获取关联的订单详情
$orderIds = json_decode($settlement['order_ids'], true);
$orders = [];

if (!empty($orderIds)) {
    $placeholders = str_repeat('?,', count($orderIds) - 1) . '?';
    $stmt = $db->prepare("SELECT o.* FROM orders o WHERE o.id IN (" . $placeholders . ")");
    $stmt->execute($orderIds);
    $orders = $stmt->fetchAll();
    
    // 处理订单的标签
    foreach ($orders as &$order) {
        $order['delivery_location_label'] = getConfigOptionLabel('delivery_location', $order['delivery_location']);
        $order['order_platform_label'] = getConfigOptionLabel('order_platform', $order['order_platform']);
        if ($order['order_screenshot']) {
            $order['screenshot_url'] = UPLOAD_URL . 'orders/' . $order['order_screenshot'];
        }
        if ($order['settlement_screenshot']) {
            $order['settlement_screenshot_url'] = UPLOAD_URL . 'settlements/' . $order['settlement_screenshot'];
        }
    }
}

$settlement['orders'] = $orders;
$settlement['order_count'] = count($orders);

// 添加结算信息
$settlement['settlement_info'] = $settlement['settlement_info'] ?? '';

// 移除敏感信息
unset($settlement['user_id']);
unset($settlement['admin_id']);

echo json_encode(['success' => true, 'data' => $settlement]);
?>